package com.cai310.lottery.task.ticket;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.cai310.lottery.common.Lottery;
import com.cai310.lottery.entity.lottery.ticket.LotterySupporter;
import com.cai310.lottery.entity.lottery.ticket.Ticket;
import com.cai310.lottery.service.lottery.jczq.JczqMatchEntityManager;
import com.cai310.lottery.service.lottery.ticket.impl.LotterySupporterEntityManager;
import com.cai310.lottery.service.lottery.ticket.impl.TicketEntityManager;
import com.cai310.lottery.support.jclq.JclqMatchItem;
import com.cai310.lottery.support.jclq.JclqPrintContent;
import com.cai310.lottery.support.jclq.JclqUtil;
import com.cai310.lottery.support.jczq.ItemBF;
import com.cai310.lottery.support.jczq.ItemBQQ;
import com.cai310.lottery.support.jczq.ItemJQS;
import com.cai310.lottery.support.jczq.ItemSPF;
import com.cai310.lottery.support.jczq.JczqMatchItem;
import com.cai310.lottery.support.jczq.JczqPrintContent;
import com.cai310.lottery.support.jczq.JczqUtil;
import com.cai310.lottery.support.jczq.PlayType;
import com.cai310.lottery.support.jczq.SchemeType;
import com.cai310.lottery.ticket.common.TicketQuery;
import com.cai310.lottery.ticket.common.TicketSupporter;
import com.cai310.lottery.ticket.common.TypeTransaction;
import com.cai310.lottery.ticket.protocol.local.disassemble.jclq.JclqPrintItem;
import com.cai310.lottery.ticket.protocol.local.disassemble.jclq.JclqPrintItemObj;
import com.cai310.lottery.ticket.protocol.local.disassemble.jczq.JczqItem;
import com.cai310.lottery.ticket.protocol.local.disassemble.jczq.JczqPrintItem;
import com.cai310.lottery.ticket.protocol.local.disassemble.jczq.JczqPrintItemObj;
import com.cai310.lottery.ticket.protocol.local.utils.CPUtil;
import com.cai310.lottery.ticket.protocol.local.utils.CpResultVisitor;
import com.cai310.lottery.ticket.protocol.local.utils.DLTCPUtil;
import com.cai310.lottery.ticket.protocol.local.utils.EL11TO5CPUtil;
import com.cai310.lottery.ticket.protocol.local.utils.JCLQCPUtil;
import com.cai310.lottery.ticket.protocol.local.utils.JCZQCPUtil;
import com.cai310.lottery.ticket.protocol.local.utils.LCZCCPUtil;
import com.cai310.lottery.ticket.protocol.local.utils.PLCPUtil;
import com.cai310.lottery.ticket.protocol.local.utils.QueryPVisitor;
import com.cai310.lottery.ticket.protocol.local.utils.SCZCCPUtil;
import com.cai310.lottery.ticket.protocol.local.utils.SFZCCPUtil;
import com.cai310.lottery.ticket.protocol.local.utils.jclq.JclqSpUtil;
import com.cai310.lottery.ticket.protocol.local.utils.jczq.JczqSpUtil;
import com.cai310.lottery.ticket.protocol.response.dto.JcMatchOddsList;
import com.cai310.utils.DateUtil;
import com.cai310.utils.JsonUtil;

public class TicketTransactionTask_betzc {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	protected TicketEntityManager ticketEntityManager;
	@Autowired
	protected LotterySupporterEntityManager lotterySupporterEntityManager;
	List<TicketQuery> ticketQuerys = new ArrayList<TicketQuery>();
	
	
	public void runTask_update() throws Exception {
		logger.info("出票同步奖金任务执行...");
		List<LotterySupporter> lotterySupporters = lotterySupporterEntityManager.findLotteryBySupporter(TicketSupporter.CAI310);
		if(lotterySupporters==null || lotterySupporters.isEmpty())return;
		
		for (LotterySupporter lotterySupporter : lotterySupporters) {
			try{
				Lottery lottery = lotterySupporter.getLotteryType();
				List<Ticket> ticketList = ticketEntityManager.findTicket_synchronedTicketByLottery(TicketSupporter.CAI310,lottery);
				if(ticketList==null || ticketList.isEmpty())continue;
				CPUtil cpUtil = null;
					for (Ticket ticket : ticketList) {
						try{
							if(lottery.equals(Lottery.SFZC)){
								cpUtil = new SFZCCPUtil();
							}else if(lottery.equals(Lottery.LCZC)){
								cpUtil = new LCZCCPUtil();
							}else if(lottery.equals(Lottery.SCZC)){
								cpUtil = new SCZCCPUtil();
							}else if(lottery.equals(Lottery.JCZQ)){
								cpUtil = new JCZQCPUtil();
							}else if(lottery.equals(Lottery.JCLQ)){
								cpUtil = new JCLQCPUtil();
							}else if(lottery.equals(Lottery.PL)){
								cpUtil = new PLCPUtil();
							}else if(lottery.equals(Lottery.DLT)){
								cpUtil = new DLTCPUtil();
							}else if(lottery.equals(Lottery.EL11TO5)){
								cpUtil = new EL11TO5CPUtil();
							}else{
								logger.error("找不到彩种所对应的出票");
								continue;
							}
							QueryPVisitor queryPVisitor= cpUtil.updateTicketPrize(ticket);
							if(!queryPVisitor.getIsSuccess()){
							    logger.error("远程出票更新中奖接口出错"+queryPVisitor.getOrderId());
							}else{
								ticket.setTicket_synchroned(Boolean.TRUE);
								ticketEntityManager.saveTicket(ticket);
							}
						}catch (Exception e) {
							logger.error("彩票｛"+ticket.getId()+"｝查询出错"+e.getMessage());
							continue;
						}
					}
			}catch (Exception e) {
				logger.error("玩法｛"+lotterySupporter.getLotteryType().getLotteryName()+"｝发票出错"+e.getMessage());
				continue;
			}
		}
		
	} 
	
	
	public void runTask_query() throws Exception {
		logger.info("出票查询任务执行...");
		List<LotterySupporter> lotterySupporters = lotterySupporterEntityManager.findLotteryBySupporter(TicketSupporter.CAI310);
		if(lotterySupporters==null || lotterySupporters.isEmpty())return;
		
		for (LotterySupporter lotterySupporter : lotterySupporters) {
			try{
				Lottery lottery = lotterySupporter.getLotteryType();
				List<Ticket> ticketList = ticketEntityManager.findSendedNoResponseTicketByLottery(TicketSupporter.CAI310,lottery);
				if(ticketList==null || ticketList.isEmpty())continue;
				CPUtil cpUtil = null;
					for (Ticket ticket : ticketList) {
						try{
							if(lottery.equals(Lottery.SFZC)){
								cpUtil = new SFZCCPUtil();
							}else if(lottery.equals(Lottery.LCZC)){
								cpUtil = new LCZCCPUtil();
							}else if(lottery.equals(Lottery.SCZC)){
								cpUtil = new SCZCCPUtil();
							}else if(lottery.equals(Lottery.JCZQ)){
								cpUtil = new JCZQCPUtil();
							}else if(lottery.equals(Lottery.JCLQ)){
								cpUtil = new JCLQCPUtil();
							}else if(lottery.equals(Lottery.PL)){
								cpUtil = new PLCPUtil();
							}else if(lottery.equals(Lottery.DLT)){
								cpUtil = new DLTCPUtil();
							}else if(lottery.equals(Lottery.EL11TO5)){
								cpUtil = new EL11TO5CPUtil();
							}else{
								logger.error("找不到彩种所对应的出票");
								continue;
							}
							queryTicket(cpUtil.confirmTicket(ticket),ticket);
						}catch (Exception e) {
							logger.error("彩票｛"+ticket.getId()+"｝查询出错"+e.getMessage());
							continue;
						}
					}
			}catch (Exception e) {
				logger.error("玩法｛"+lotterySupporter.getLotteryType().getLotteryName()+"｝发票出错"+e.getMessage());
				continue;
			}
		}
		
	} 
	
	public void runTask() throws Exception {
		logger.info("出票交易任务执行...");
		List<LotterySupporter> lotterySupporters = lotterySupporterEntityManager.findLotteryBySupporter(TicketSupporter.CAI310);
		if(lotterySupporters==null || lotterySupporters.isEmpty())return;
		
		for (LotterySupporter lotterySupporter : lotterySupporters) {
			try{
				Lottery lottery = lotterySupporter.getLotteryType();
				List<Ticket> ticketList = ticketEntityManager.findTicket(TicketSupporter.CAI310,lottery);
				if(ticketList==null || ticketList.isEmpty())continue;
				CPUtil cpUtil = null;
					for (Ticket ticket : ticketList) {
						try{
							if(lottery.equals(Lottery.SFZC)){
								cpUtil = new SFZCCPUtil();
							}else if(lottery.equals(Lottery.LCZC)){
								cpUtil = new LCZCCPUtil();
							}else if(lottery.equals(Lottery.SCZC)){
								cpUtil = new SCZCCPUtil();
							}else if(lottery.equals(Lottery.JCZQ)){
								cpUtil = new JCZQCPUtil();
							}else if(lottery.equals(Lottery.JCLQ)){
								cpUtil = new JCLQCPUtil();
							}else if(lottery.equals(Lottery.PL)){
								cpUtil = new PLCPUtil();
							}else if(lottery.equals(Lottery.DLT)){
								cpUtil = new DLTCPUtil();
							}else if(lottery.equals(Lottery.EL11TO5)){
								cpUtil = new EL11TO5CPUtil();
							}else{
								logger.error("找不到彩种所对应的出票");
								continue;
							}
							sendTicket(cpUtil.sendTicket(ticket),ticket);
						}catch (Exception e) {
							logger.error("彩票｛"+ticket.getId()+"｝发票出错"+e.getMessage());
							continue;
						}
					}
			}catch (Exception e) {
				logger.error("玩法｛"+lotterySupporter.getLotteryType().getLotteryName()+"｝发票出错"+e.getMessage());
				continue;
			}
		}
		
	}
	public static void main(String[] args) throws IOException {
	}
	
	
	/**
	 * 处理彩票
	 * @param
	 * @param 
	 * @return
	 * @throws IOException
	 */
	private void sendTicket(CpResultVisitor cpResultVisitor,Ticket ticket) throws IOException{
		if(cpResultVisitor.getIsSuccess()){
			logger.error(TicketSupporter.CAI310.getSupporterName()+"发送票成功，返回代码："+cpResultVisitor.getResult());
			    ticket.setSended(Boolean.TRUE);
				ticket.setSendTime(new Date());
				ticket.setStateCode("0");
				ticket.setStateModifyTime(new Date());
				ticket.setOrderNo(cpResultVisitor.getOrderId());
				ticketEntityManager.saveTicket(ticket);
		}else{
			ticket.setSendTime(new Date());
			ticketEntityManager.saveTicket(ticket);
			logger.error(TicketSupporter.CAI310.getSupporterName()+"发送票出错，返回代码："+cpResultVisitor.getResult());
		}
	}
	/**
	 * 查询彩票
	 * @param
	 * @param 
	 * @return
	 * @throws IOException
	 */
	private void queryTicket(QueryPVisitor queryPVisitor,Ticket ticket) throws IOException{
		if(queryPVisitor.getIsSuccess()){
			logger.debug(TicketSupporter.CAI310.getSupporterName()+"{"+ticket.getId()+"}查票票成功，返回代码："+queryPVisitor.getResultId());
			System.out.println(TicketSupporter.CAI310.getSupporterName()+"{"+ticket.getId()+"}查票票成功，返回代码："+queryPVisitor.getResultId());
			ticket.setStateCode("1");
			ticket.setStateModifyTime(new Date());
			ticket.setRemoteTicketId(queryPVisitor.getTicketCode());
			ticket.setTicketTime(StringUtils.isBlank(queryPVisitor.getOperateTime())?null:DateUtil.strToDate(queryPVisitor.getOperateTime(), "yyyy-MM-dd hh:mm:ss"));
		    if(ticket.getLotteryType().equals(Lottery.JCZQ)){
		    	@SuppressWarnings("rawtypes")
				Map classMap = new HashMap();
				classMap.put("items", JczqPrintItem.class);
				JczqPrintItemObj jczqPrintItemObj = JsonUtil.getObject4JsonString(ticket.getContent(), JczqPrintItemObj.class, classMap);
				if(null!=jczqPrintItemObj){
			    	JcMatchOddsList jcMatchOddsList = JczqSpUtil.parseResponseSp(queryPVisitor.getAwards(),jczqPrintItemObj,ticket);
			    	if(null!=jcMatchOddsList&&null!=jcMatchOddsList.getJcMatchOdds()&&!jcMatchOddsList.getJcMatchOdds().isEmpty()){
						jcMatchOddsList.setTicketIndex(jczqPrintItemObj.getTicketIndex());
						String awardString = JsonUtil.getJsonString4JavaPOJO(jcMatchOddsList);
						if(StringUtils.isNotBlank(awardString))ticket.setExtension(awardString);	
					}
				}

		   }else if(ticket.getLotteryType().equals(Lottery.JCLQ)){
			    @SuppressWarnings("rawtypes")
				Map classMap = new HashMap();
				classMap.put("items", JclqPrintItem.class);
				JclqPrintItemObj jclqPrintItemObj = JsonUtil.getObject4JsonString(ticket.getContent(), JclqPrintItemObj.class, classMap);
				if(null!=jclqPrintItemObj){
			    	JcMatchOddsList jcMatchOddsList = JclqSpUtil.parseResponseSp(queryPVisitor.getAwards(),jclqPrintItemObj,ticket);
			    	if(null!=jcMatchOddsList&&null!=jcMatchOddsList.getJcMatchOdds()&&!jcMatchOddsList.getJcMatchOdds().isEmpty()){
						jcMatchOddsList.setTicketIndex(jclqPrintItemObj.getTicketIndex());
						String awardString = JsonUtil.getJsonString4JavaPOJO(jcMatchOddsList);
						if(StringUtils.isNotBlank(awardString))ticket.setExtension(awardString);	
					}
				}
						
		   }
		}else{
			if("2".equals(queryPVisitor.getResultId())){
				///撤单
				ticket = ticketEntityManager.getTicket(ticket.getId());
				System.out.println(TicketSupporter.CAI310.getSupporterName()+"{"+ticket.getId()+"}查票票成功，返回代码："+queryPVisitor.getResultId());
				ticket.setStateCode("2");
				ticket.setTicketTime(StringUtils.isBlank(queryPVisitor.getOperateTime())?null:DateUtil.strToDate(queryPVisitor.getOperateTime(), "yyyy-MM-dd hh:mm:ss"));
				ticket.setStateModifyTime(new Date());
				ticketEntityManager.saveTicket(ticket);
			}
		}
		ticketEntityManager.saveTicket(ticket);
	}
}
